package cn.edu.hstc.wm.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.Constants;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.adapter.StoreItemMenuAdapter;
import cn.edu.hstc.wm.bean.Good;
import cn.edu.hstc.wm.bean.Store;
import cn.edu.hstc.wm.service.AppConfigService;
import cn.edu.hstc.wm.service.GoodService;
import cn.edu.hstc.wm.service.Test;
import cn.edu.hstc.wm.ui.GoOrder;
import cn.edu.hstc.wm.ui.StoreItemActivity;
import cn.edu.hstc.wm.ui.UIHelper;
import cn.edu.hstc.wm.ui.UserLoginDialog;
import cn.edu.hstc.wm.ui.base.BaseFragment;
import cn.edu.hstc.wm.utils.IntentUtil;
import cn.edu.hstc.wm.utils.LogUtil;
import cn.edu.hstc.wm.widget.CustomToast;
import cn.edu.hstc.wm.widget.XListView;
import cn.edu.hstc.wm.widget.XListView.IXListViewListener;

/**
 * 进入店铺后显示店铺菜单的Fragment
 */
public class StoreItemMenu extends BaseFragment implements IXListViewListener, StoreItemMenuAdapter.CallBack, OnItemClickListener, OnItemLongClickListener, LoadFailedFragment.CallBack {

	public static final String TAG = "StoreItemMenu";
	public static final String GO_ORDER_STORE = "GO_ORDER_STORE";
	public static final String GO_ORDER_GOODS_LIST = "GO_ORDER_GOODS_LIST";
	public static final String GO_ORDER_LIST_COUNT = "GO_ORDER_LIST_COUNT";
	public static final String GO_ORDER_LIST_PRICE = "GO_ORDER_LIST_PRICE";

	private Context mContext;

	/** Fragment 需要设置的显示方法类型 */
	private final int FRAGMENT_TYPE_REMOVE = 0x00;
	private final int FRAGMENT_TYPE_ADD = 0x01;
	private final int FRAGMENT_TYPE_REPLACE = 0x02;

	/** 当前最后一个数据所在的位置 */
	private int mCurDataIndex = 0;
	/** 最大的位置 */
	private int mMaxIndex = 0;

	/** 获取到的店铺实体类 */
	private Store mStore;
	/** 根据获取到的store来获取该store下所有的menu */
	private List<Good> mGoods;
	/** 当前选中的菜单集合 */
	private HashSet<Good> selectTotalGoods;

	/** 根视图 */
	private View rootView;

	// 菜单条目
	private XListView xListView;
	private StoreItemMenuAdapter mAdapter;

	/** 当前选中了的菜单总份数 */
	private int mHasSelectCount = 0;
	/** 当前选中的菜单总价格 */
	private float mHasSelectPrice = 0;

	/** 购物车栏目 */
	private View mShopCarView;
	/** 当前点击该店铺所有的菜单份数 */
	private TextView mHasSelectCountView;
	/** 清空所有选中的item,垃圾箱 */
	private ImageButton mClearHasSelect;
	/** 选中item 的总价 */
	private TextView mHasSelectPriceView;
	/** 去下单 */
	private TextView mGoOrder;

	/** 正在加载界面 */
	private LoadingFragment mLoadingFragment;

	/** 加载失败页面 */
	private LoadFailedFragment mLoadFailedFragment;

	private Handler mHandler;

	/**
	 * 获取StoreItemMenu实例的方法
	 * 
	 * @param bundle
	 * @return
	 */
	public static StoreItemMenu getInstance(Bundle bundle) {
		StoreItemMenu storeItemMenu = new StoreItemMenu();
		storeItemMenu.setArguments(bundle);
		return storeItemMenu;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mContext = this.getActivity();
		rootView = inflater.inflate(R.layout.store_item_menu_fragment_layout, null);
		mStore = (Store) getArguments().getSerializable(StoreItemActivity.INTENT_URL);

		new GetGoodsCountTask().execute(mStore.getId());
		// 设置为正在加载
		showLoadingView(true);

		// initData();
		initListView();
		initShopCart();
		mHandler = new Handler();
		return rootView;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult" + " reqeustCode = " +resultCode + " resultCode = " + resultCode);
		
		switch (resultCode) {
		case Constants.LOGIN_TYPE_GO_ORDER:
			goOrder();
			break;

		case Activity.RESULT_OK:
			// 当提交成功后
			Log.d(TAG, "" + requestCode + "   " + resultCode + "   " + data.toString());
			// 清空购物车
			mHasSelectCount = 0;
			mHasSelectPrice = 0;
			selectTotalGoods.clear(); // 清空
			mHasSelectCountView.setText("");// 总份数清零
			mHasSelectPriceView.setText(""); // 总价清零
			break;

		case Activity.RESULT_CANCELED:
			// 取消操作
			break;
		default:
			break;
		}

	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		new GetDataTask().execute(0);
	}

	/**
	 * 开始执行获取数据的任务
	 * 
	 * @param index
	 *            数据开始位置
	 */
	private void startDataTask(int index) {
		if (index >= mMaxIndex) {
			CustomToast.make(getActivity()).setText("已经到最后了(⊙o⊙)…!").show();
			return;
		} else {
			new GetDataTask().execute(index);
		}
	}

	/**
	 * 设置是否显示正在加载界面
	 * 
	 * @param flag
	 *            true 显示正在加载 ;false 不显示正在加载
	 */
	private void showLoadingView(boolean flag) {
		if (flag) {
			// 正在加载页面显示
			mLoadingFragment = LoadingFragment.getInstance(getArguments());
			manageFragment(FRAGMENT_TYPE_REPLACE, mLoadingFragment);
		} else {
			// 移除正在加载显示页面
			if (mLoadingFragment != null) {
				manageFragment(FRAGMENT_TYPE_REMOVE, mLoadingFragment);
			}
		}
	}

	/**
	 * 设置是否显示加载失败界面
	 * 
	 * @param flag
	 *            true 显示失败界面;false 不显示失败界面
	 */
	private void showLoadFailedView(boolean flag) {
		if (flag) {
			// 显示加载失败的界面
			mLoadFailedFragment = LoadFailedFragment.getInstance(getArguments());
			manageFragment(FRAGMENT_TYPE_REPLACE, mLoadFailedFragment);
		} else {
			// 移除加载失败的界面
			if (mLoadFailedFragment != null) {
				manageFragment(FRAGMENT_TYPE_REMOVE, mLoadFailedFragment);
			}
		}
	}

	/**
	 * Fragment管理设置
	 * 
	 * @param type
	 *            动作类型: 0 -> remove ; 1 -> add ; 2 -> replace
	 * @param fragment
	 *            需要管理的Fragment
	 */
	private void manageFragment(int type, Fragment fragment) {
		// 在Fragment中管理子Fragment是使用 getChildFragmentManager()
		FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

		switch (type) {
		// remove
		case FRAGMENT_TYPE_REMOVE:
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				// FIXME 错误
				// transaction.setCustomAnimations(R.animator.fragment_slide_left_enter,
				// R.animator.fragment_slide_left_exit);
			} else {
				transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			}
			transaction.remove(fragment);
			transaction.commit();
			break;
		// add
		case FRAGMENT_TYPE_ADD:
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			transaction.add(fragment, "add");
			transaction.commit();
			break;

		// replace
		case FRAGMENT_TYPE_REPLACE:
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
			transaction.replace(R.id.fl_store_item_menu_fragment, fragment);
			transaction.commit();
			break;
		default:
			break;
		}

	}

	/** 初始化ListView列表 */
	private void initListView() {
		mGoods = new ArrayList<Good>();

		xListView = (XListView) rootView.findViewById(R.id.xListView_store_item_menu_fragment);
		xListView.setPullLoadEnable(true);// 允许上拉加载更多
		xListView.setPullRefreshEnable(true); // 允许下拉刷新

		mAdapter = new StoreItemMenuAdapter(getActivity(), mGoods, this);

		xListView.setAdapter(mAdapter);
		xListView.setOnItemClickListener(this);
		xListView.setOnItemLongClickListener(this);
		xListView.setXListViewListener(this);
	}

	/** 初始化购物车栏目 */
	private void initShopCart() {
		mShopCarView = (View) rootView.findViewById(R.id.store_item_menu_fragment_shopcart);
		mHasSelectCountView = (TextView) rootView.findViewById(R.id.tv_store_item_menu_select_all_count);
		mClearHasSelect = (ImageButton) rootView.findViewById(R.id.iv_store_item_menu_clear_all_select);
		mHasSelectPriceView = (TextView) rootView.findViewById(R.id.tv_store_item_menu_select_all_price);
		mGoOrder = (TextView) rootView.findViewById(R.id.tv_store_item_menu_goOrder);

		selectTotalGoods = new HashSet<Good>();
		mShopCarView.setVisibility(View.GONE); // 开始先隐藏购物车栏,等到有添加菜单后才显示出来
		// 监听点击事件
		ShopCartListener l = new ShopCartListener();
		mClearHasSelect.setOnClickListener(l);
		mGoOrder.setOnClickListener(l);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.v(TAG, "onActivityCreated");
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mGoods.clear();
				mCurDataIndex = 0;
				startDataTask(mCurDataIndex);
				onLoad();
			}
		}, 1500);

	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				startDataTask(mCurDataIndex);
				onLoad();
			}
		}, 1500);
	}

	@SuppressLint("SimpleDateFormat")
	public void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		xListView.setRefreshTime(new SimpleDateFormat("HH:mm:ss") // 更新时间设置
				.format(new Date(System.currentTimeMillis())) + "");
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// 点击某个菜单显示详细内容的对话框
		StoreItemMenuInfoDialog.newInstance((Good) parent.getAdapter().getItem(position)).show(getFragmentManager(), "no title");
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO 长按删除该菜单
		Log.d(TAG, "删除你这个一选中的菜单" + arg2);

		// return true 长按时不会让点击事件捕获到,false时点击事件也能捕获到
		return true;
	}

	/**
	 * 购物车监听器
	 */
	private final class ShopCartListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			// 清空所有选择
			case R.id.iv_store_item_menu_clear_all_select:
				clearShopCat();
				break;
			// 去下单
			case R.id.tv_store_item_menu_goOrder:
				goOrder();
				break;
			default:
				break;
			}
		}

	}

	private void clearShopCat() {
		CustomToast.make(mContext).setText("清空已选择的菜单").show();
		// mAdapter.notifyDataSetInvalidated();
		// mGoods.clear();
		// mGoods.addAll(Test.getGoodsByStore(mStore));
		// xListView.setAdapter(mAdapter);
		// mAdapter.notifyDataSetChanged();
		mHasSelectCount = 0;
		mHasSelectPrice = 0;
		selectTotalGoods.clear(); // 清空
		mHasSelectCountView.setText("");// 总份数清零
		mHasSelectPriceView.setText(""); // 总价清零
		// 清除所有的item 显示份数?
	}

	/**
	 * 去下单了
	 */
	private void goOrder() {
		// 购物车不为空
		if (selectTotalGoods.size() > 0) {
			Bundle bundle = new Bundle();
			bundle.putSerializable(GO_ORDER_STORE, mStore);
			bundle.putSerializable(GO_ORDER_GOODS_LIST, selectTotalGoods);// 选中的菜单
			bundle.putInt(GO_ORDER_LIST_COUNT, mHasSelectCount); // 总份数
			bundle.putFloat(GO_ORDER_LIST_PRICE, mHasSelectPrice);// 总价

			// startActivityForResult(intent, 0);
			// 登录后才能下单
			UIHelper.goOrder(getActivity(), bundle);
		} else {
			CustomToast.make(mContext).setText("还没有选择菜单呢,赶紧去选择菜单吧").show();
		}
	}

	public void onMenuItemClick(int position) {

		Log.d(TAG, position + "");
		// 选中了某菜单
		Good good = mGoods.get(position);
		good.setSelectCount(good.getSelectCount() + 1);

		// 总价 = 原总价+ 菜单.价格
		mHasSelectPrice += good.getPrice();

		// 点击一下就加一个
		mHasSelectCount++;

		mHasSelectCountView.setText(mHasSelectCount + ""); // 设置显示的总份数
		mHasSelectPriceView.setText(mHasSelectPrice + "");// 设置显示的总价
		mShopCarView.setVisibility(View.VISIBLE); // 显示购物车

		// 添加到以选中
		selectTotalGoods.add(good);
	}

	/**
	 * 获取Good数据的异步任务
	 */
	private class GetDataTask extends AsyncTask<Integer, Integer, List<Good>> {

		// 执行后台线程
		protected List<Good> doInBackground(Integer... params) {
			try {
				// 店铺id , 查询页的起始位置, 每页查询的数据量
				return GoodService.getGoodsList(mStore.getId(), params[0], AppConfigService.getItemCount(getActivity()));
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		// 执行开始
		protected void onPreExecute() {
			LogUtil.d(TAG, "GetDataTask start");
			super.onPreExecute();
		}

		// 执行后台线程结束后
		protected void onPostExecute(List<Good> result) {
			if (result != null) {
				mGoods.addAll(result);
				mAdapter.notifyDataSetChanged();
				mCurDataIndex = mCurDataIndex + result.size();
				showLoadingView(false);
			} else {
				// 错误提示
				Log.d(TAG, "onPostExecute  " + result);
				showLoadFailedView(true);
			}
		}

		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		protected void onCancelled(List<Good> result) {
			// TODO Auto-generated method stub
			super.onCancelled(result);
		}

		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

	}

	/**
	 * @ClassName: GetGoodsCountTask
	 * @Description: 根据店铺id获取该店铺所有商品的个数
	 * 
	 * @ModificationHistory
	 */
	private final class GetGoodsCountTask extends AsyncTask<Integer, Integer, Integer> {

		@Override
		protected Integer doInBackground(Integer... params) {
			try {
				return GoodService.getGoodsCountByStoreId(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		}

		@Override
		protected void onPreExecute() {
			LogUtil.i(TAG, "GetGoodsCountTask start");
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Integer result) {
			LogUtil.i(TAG, "GetGoodsCountTask end , the result = " + result);
			mMaxIndex = result;
			initData();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	// 加载失败的回调接口
	public void flush() {
		// 移除加载失败界面
		showLoadFailedView(false);
		// 显示正在加载界面
		showLoadingView(true);
		// 刷新数据
		onRefresh();
	}
}
